//
//  EMLoginViewController.swift
//  Hyphenate-Demo-Swift
//
//  Created by dujiepeng on 2017/6/13.
//  Copyright 2017 dujiepeng. All rights reserved.
//

import UIKit
import MBProgressHUD
import Hyphenate


class EMLoginViewController: UIViewController, UITextFieldDelegate {
    
    @IBOutlet weak var usernameTextField: UITextField!
    @IBOutlet weak var passwordTextField: UITextField!
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var showResetPassword: UIButton!
    @IBOutlet weak var changeButton: UIButton!
    @IBOutlet weak var loginView: UIView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setBackgroundColor()
        setupUI()
//        setupForDismissKeyboard()
//        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillChangeFrame(noti:)), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)  
        UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent  
    }
    
    func setupUI () {
        usernameTextField.delegate = self  
        usernameTextField.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 15, height: usernameTextField.height()))  
        usernameTextField.leftViewMode = UITextFieldViewMode.always  
        
        passwordTextField.delegate = self  
        passwordTextField.leftView = UIView.init(frame: CGRect(x: 0, y: 0, width: 15, height: passwordTextField.height()))  
        passwordTextField.leftViewMode = UITextFieldViewMode.always  
        
        loginButton.top(top: kScreenHeight - loginButton.height())  
        loginButton.width(width: kScreenWidth)  
        
    }
    
    func setBackgroundColor () {
        let gradient = CAGradientLayer.init()  
        gradient.frame = UIScreen.main.bounds  
        gradient.colors =  [LaunchTopColor.cgColor, LaunchBottomColor.cgColor]  
        gradient.startPoint = CGPoint.init(x: 0.0, y: 0.0)  
        gradient.endPoint = CGPoint.init(x: 0.0, y: 1.0)  
        view.layer.insertSublayer(gradient, at: 0)  
    }
    
    @IBAction func loginAction(_ sender: UIButton) {
        
        if _isEmpty() {
            return
        }
        
        MBProgressHUD.showAdded(to: view, animated: true)
        weak var weakSelf = self
        let defaults = UserDefaults.standard
        var token = defaults.string(forKey: "token")
        
        let username = usernameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let md5Password = md5(String(passwordTextField.text!))
        
        let parameters = [
            "loginType": "password",
            "deviceType":"1",
            "deviceToken":token,
            "username":username,
            "password":md5Password
            ] as [String : Any] as [String : Any]
        CUHTTP.instance().makePostData(url: "login", parameters:parameters, success: { (response) in
            if let value = response?.result.value {
                let data = value.data(using: String.Encoding.utf8)! as NSData
                let json = try? JSONSerialization.jsonObject(with: data as Data,
                                                             options:.allowFragments) as! [String: Any]
                let loopE = json as! [String: Any]
                if let tmpStr0 = loopE["image"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        let defaults = UserDefaults.standard
                        defaults.set(CUHTTP.URL.ROOT + "/"+tmpStr1, forKey: username!+"_avatar")
                    }
                }
                if let tmpStr0 = loopE["firstName"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        let defaults = UserDefaults.standard
                        defaults.set(tmpStr1 + " " + (loopE["lastName"] as! String), forKey: username!+"_nickname")
                    }
                }
                if let tmpStr0 = loopE["authToken"] {
                    if let tmpStr1 = (tmpStr0 as? String) {
                        let defaults = UserDefaults.standard
                        defaults.set(tmpStr1, forKey: "authToken")
                    }
                }
                
                
                EMClient.shared().login(withUsername: username, password: md5Password) { (username, error) in
                    
                    if error == nil {
                        
                        MBProgressHUD.hide(for: weakSelf?.view, animated: true)
                        EMClient.shared().options.isAutoLogin = true
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue:KNOTIFICATION_LOGINCHANGE), object: NSNumber(value: true))
                        
                    } else {
                        
                        MBProgressHUD.hide(for: weakSelf?.view, animated: true)
                        var alertStr = ""
                        switch error!.code {
                        case EMErrorUserNotFound:
                            alertStr = error!.errorDescription
                            break
                        case EMErrorNetworkUnavailable:
                            alertStr = error!.errorDescription
                            break
                        case EMErrorServerNotReachable:
                            alertStr = error!.errorDescription
                            break
                        case EMErrorUserAuthenticationFailed:
                            alertStr = error!.errorDescription
                            break
                        case EMErrorServerTimeout:
                            alertStr = error!.errorDescription
                            break
                        default:
                            alertStr = error!.errorDescription
                            break
                        }
                        
                        let alertView = UIAlertView.init(title: nil, message: alertStr, delegate: nil, cancelButtonTitle: "okay")
                        alertView.show()
                    }
                }
            }
            
            
            
            
        }) { (response) in
            MBProgressHUD.hide(for: weakSelf?.view, animated: true)
            self.show(response ?? "")
        }
        
    }
   
    @IBAction func showResetPassword(_ sender: UIButton) {
         performSegue(withIdentifier: "LoginToResetPassword", sender: self)
    }
    
    
    
    
    func md5(_ string: String) -> String {
        let context = UnsafeMutablePointer<CC_MD5_CTX>.allocate(capacity: 1)
        var digest = Array<UInt8>(repeating:0, count:Int(CC_MD5_DIGEST_LENGTH))
        CC_MD5_Init(context)
        CC_MD5_Update(context, string, CC_LONG(string.lengthOfBytes(using: String.Encoding.utf8)))
        CC_MD5_Final(&digest, context)
        context.deallocate(capacity: 1)
        var hexString = ""
        for byte in digest {
            hexString += String(format:"%02x", byte)
        }
        return hexString
    }
    
    
    @IBAction func doChangeState(_ sender: UIButton) {
        
        performSegue(withIdentifier: "LoginToRegister", sender: self)
//        isEditing = true
//        if signupButton.isHidden == true {
//            loginButton.isHidden = true
//            signupButton.isHidden = false
//            changeButton.setTitle("Log in", for: UIControlState.normal)
//            tipLabel.text = "Have an account?"
//        } else {
//            loginButton.isHidden = false
//            signupButton.isHidden = true
//            changeButton.setTitle("Sign up", for: UIControlState.normal)
//            tipLabel.text = "Yay! New to Hyphenate?"
//        }
    }
    
    // MARK: - UITextFieldDelegate
    
    func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
        if textField == usernameTextField {
            passwordTextField.text = ""  
        }
        
        return true  
    }
    
    func textFieldShouldReturn(_ textField: UITextField) -> Bool {
        if textField == usernameTextField {
            passwordTextField.becomeFirstResponder()  
        } else if textField == passwordTextField {
            passwordTextField.resignFirstResponder()
            loginAction(loginButton)
        }
        
        return true  
    }
    
    // MARK: - private
    
    fileprivate func _isEmpty() -> Bool {
        
        let username = usernameTextField.text?.trimmingCharacters(in: .whitespacesAndNewlines).lowercased()
        let password = passwordTextField.text  

        
        if (username?.count)! == 0 || (password?.count)! == 0 {
            let alertView = UIAlertView.init(title: "reminder".localized(), message: "please enter username and password".localized(), delegate: nil, cancelButtonTitle: "okay")
            alertView.show()
            
            return true
        }
        
        if !(isValidUname(testStr: username!)) {
            let alertView = UIAlertView.init(title: "reminder".localized(), message: "invalid usernmame".localized(), delegate: nil, cancelButtonTitle: "okay")
            alertView.show()
            
            return true
        }
        return false
    }
    func isValidUname(testStr:String) -> Bool {
        let emailRegEx = "[A-Z0-9a-z._]{1,64}"
        
        let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
        return emailTest.evaluate(with: testStr)
    }
    // MARK: - notification
//    @objc func keyboardWillChangeFrame(noti: NSNotification) {
//        let userInfo = (noti.userInfo as! Dictionary<String, NSValue>)
//        let beginValue = userInfo["UIKeyboardFrameBeginUserInfoKey"]!
//        let endValue = userInfo["UIKeyboardFrameEndUserInfoKey"]!
//
//        var beginRect = CGRect()
//        var endRect = CGRect()
//        beginValue.getValue(&beginRect)
//        endValue.getValue(&endRect)
//
//        var btnFrame = CGRect()
//        var top: CGFloat = 0
//
//            btnFrame = loginButton.frame
//
//        if endRect.origin.y == view.height() {
//            btnFrame.origin.y = kScreenHeight - btnFrame.size.height
//        } else if (beginRect.origin.y == view.height()) {
//            btnFrame.origin.y = kScreenHeight - btnFrame.size.height - endRect.size.height + 100
//            top = -100
//        } else {
//            btnFrame.origin.y = kScreenHeight - btnFrame.size.height - endRect.size.height + 100
//            top = -100
//        }
//
//        weak var weakSelf = self
//        UIView.animate(withDuration: 0.3) {
//            UIApplication.shared.keyWindow?.top(top: top)
//            weakSelf?.loginButton.frame = btnFrame
//        }
//
//    }
}
